package com.lx.lock.reentant;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description:tryLock()，当锁对象没有被其他线程持有的情况下，才会获得该锁
 * @Author: LinXin_
 * @CreateTime: 2021/4/18 12:54
 */
public class Test08 {
    static class Service {
        private  ReentrantLock lock = new ReentrantLock();

        public  void ServiceMethod() {
            try {
                if(lock.tryLock()) {
                    System.out.println(Thread.currentThread().getName()+"获得锁定");
                    Thread.sleep(3000);     //模拟执行任务的时长
                }else {
                    System.out.println(Thread.currentThread().getName()+"没有获得锁定");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if(lock.isHeldByCurrentThread()){
                    lock.unlock();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Service service = new Service();
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                service.ServiceMethod();
            }
        };
        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r1);

        t1.start();
        Thread.sleep(50);   //睡眠50毫秒确保t1线程锁定
        t2.start();
    }
}
